package com.wu.shiro;

import com.wu.pojo.po.userPo.User;
import com.wu.service.UserService;
import com.wu.utils.JwtUtils;
import com.wu.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.wu.constants.Constants.TOKEN;


@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 认证.登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
        JwtToken jwt = (JwtToken) authToken;
        log.info("jwt----------------->{}", jwt);
        String token = (String) jwt.getCredentials();
        String userToken = (String)redisUtil.get(TOKEN.concat(token));
        if (userToken == null) {
            throw new AuthenticationException("Login has expired. Please log in again!");
        }
        redisUtil.expire(TOKEN.concat(token),1000*60*5); //重新设置过期时间

        String userId = null;
        try {
            userId = JwtUtils.getClaimByToken(userToken).getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("The token has expired!");
        }
        User user = userService.selectOne(new User().setId(userId));
        if(user == null) {
            throw new UnknownAccountException("Account does not exist！");
        }
        if(user.getStatus() == -1) {
            throw new LockedAccountException("The account has been locked！");
        }


        return new SimpleAuthenticationInfo(user, userToken, "AccountRealm");
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        log.info("授权-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();

        authorizationInfo.addRole(user.getRole());

        return authorizationInfo;
    }

}
